package com.fanshuai.tree.tree;

import com.fanshuai.tree.Visitor;

import java.util.Iterator;

public class Tree implements ITree {
    public Node root;

    @Override
    public void setRoot(int value) {
        root = new Node(value);
    }

    @Override
    public void addNode(Node node, Node subNode) {
        subNode.parent = node;
        node.subNodes.add(subNode);
    }

    @Override
    public void addNode(Node node, Node subNode, int index) throws IndexOutOfBoundsException {
        int length = node.subNodes.size();
        if (index < 0 || index > length) {
            throw new IndexOutOfBoundsException("index out of bounds, index=" + index);
        }

        subNode.parent = node;
        node.subNodes.add(index, subNode);
    }

    @Override
    public void delNode(Node node, int value) {
        Iterator<Node> iterator = node.subNodes.iterator();
        while (iterator.hasNext()) {
            Node subNode = iterator.next();
            if (subNode.value == value) {
                subNode.parent = null;
                iterator.remove();
            }
        }
    }

    @Override
    public void delNodeByIndex(Node node, int index) {
        int length = node.subNodes.size();
        if (index < 0 || index > length) {
            throw new IndexOutOfBoundsException("index out of bounds, index=" + index);
        }

        Node subNode = node.subNodes.get(index);
        subNode.parent = null;
        node.subNodes.remove(index);
    }

    @Override
    public void clear() {
        root = null;
    }

    @Override
    public void visit(Visitor visitor) {
        visit(root, visitor);
    }

    private void visit(Node node, Visitor visitor) {
        if (null == node) {
            return;
        }

        visitor.visit(node.value);
        for (Node subNode : node.subNodes) {
            visit(subNode, visitor);
        }
    }
}
